package com.zhuhjay.service.system.util;

import cn.hutool.extra.servlet.ServletUtil;
import com.zhuhjay.common.base.enums.HttpCode;
import com.zhuhjay.common.base.util.JacksonUtils;
import com.zhuhjay.common.base.util.SpringContextHolder;
import com.zhuhjay.common.base.util.StrUtils;
import com.zhuhjay.common.core.util.IpAddressUtils;
import com.zhuhjay.common.security.context.LoginUserContext;
import com.zhuhjay.common.web.util.ServletUtils;
import com.zhuhjay.service.system.model.entity.SystemLog;
import com.zhuhjay.service.system.service.SystemLogService;

import javax.servlet.http.HttpServletRequest;

/**
 * @author ZhuHJay
 * @date 2023/12/12 16:32
 */
public class LogUtil {

    private static final SystemLogService LOG_SERVICE =
            SpringContextHolder.getBean(SystemLogService.class);

    /**
     * 记录日志
     * @param methodName    方法签名
     * @param methodDesc    方法描述
     * @param reqData       请求参数 => 可以 null
     * @param respResult    响应结果 => 可以 null
     * @param code          响应状态码
     * @param processTime   处理时长 => 单位ms, 0为未知
     */
    public static void record(
            String methodName, String methodDesc, Object reqData,
            Object respResult, HttpCode code, Integer processTime) {
        SystemLog log = new SystemLog();
        String reqStr = null;
        String respStr = null;
        if (reqData != null) {
            reqStr = reqData instanceof String ? (String) reqData : JacksonUtils.writeValueAsString(reqData);
        }
        if (respResult != null) {
            respStr = respResult instanceof String ? (String) respResult : JacksonUtils.writeValueAsString(respResult);
            respStr = StrUtils.subStr(respStr, 1500);
        }
        log
                .setMethodName(methodName)
                .setMethodDesc(methodDesc)
                .setRequestData(reqStr)
                .setResponseResult(respStr)
                .setResponseCode(code.getCode())
                .setProcessTime(processTime);
        baseInfoFill(log);
        LOG_SERVICE.save(log);
    }

    /** 填充其余普通信息 */
    private static void baseInfoFill(SystemLog log) {
        HttpServletRequest request = ServletUtils.currentRequest();
        String ip = ServletUtil.getClientIP(request);
        log
                .setRequestMethod(request.getMethod())
                .setRequestUserId(LoginUserContext.getUserId())
                .setRequestUrl(request.getRequestURI())
                .setRequestIp(ip)
                .setRequestLocation(IpAddressUtils.getRealAddressByIp(ip));
    }

}
